package com.cgsd.heyu.ad;


import android.app.Activity;
import android.util.Log;
import android.view.View;

import com.android.library.utils.BeanUtils;
import com.apkfuns.logutils.LogUtils;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.cgsd.heyu.api.AppConfig;
import com.cgsd.heyu.entity.AdContentEntity;
import com.cgsd.heyu.utils.UIUtils;
import com.qq.e.ads.rewardvideo.RewardVideoAD;
import com.qq.e.ads.rewardvideo.RewardVideoADListener;
import com.qq.e.comm.util.AdError;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * Description :  模板渲染Draw视频广告
 *
 * @author : xiaoxing
 * 时间：2020/3/13 09
 * 邮箱：only_dream136@sina.com
 */
public class AdDrawVideo {

    private String TAG = "AdDrawVideo : ";
    /**
     * 穿山甲相关
     */
    private TTRewardVideoAd mttRewardVideoAd;
    private TTAdNative mTTAdNative;
    /**
     * 广点通相关
     */
    private RewardVideoAD rewardVideoAD;

    private AdContentEntity adContentEntity;
    private WeakReference<Activity> weakReference;
    private AdListener adListener;
    private int showType = -1;

    public AdDrawVideo(Activity activity, AdContentEntity entity, AdListener adListener) {
        this.adListener = adListener;
        weakReference = new WeakReference<>(activity);
        this.adContentEntity = entity;

        if (BeanUtils.isEmpty(adContentEntity)) {
            return;
        }
        if (AdContentEntity.CHUANSHANJIA.equals(adContentEntity.platformType)) {
            mTTAdNative = TTAdSdk.getAdManager().createAdNative(weakReference.get());
        }

    }

    /**
     * 加载广告
     */
    public void loadAd() {
        if (AdContentEntity.GUANGDIANTONG.equals(adContentEntity.platformType)) {
            adRewardVideoG();
        } else {
            adRewardVideoC();
        }
    }

    /**
     * 加载广点通开屏甲短视频广搞
     */
    private void adRewardVideoG() {
        rewardVideoAD = new RewardVideoAD(weakReference.get(), adContentEntity.advertisingId, new RewardVideoADListener() {
            @Override
            public void onADLoad() {
                if (adListener != null) {
                    adListener.onSuccess(null);
                }
                rewardVideoAD.showAD(weakReference.get());
            }

            @Override
            public void onVideoCached() {

            }

            @Override
            public void onADShow() {

            }

            @Override
            public void onADExpose() {

            }

            @Override
            public void onReward() {

            }

            @Override
            public void onADClick() {

            }

            @Override
            public void onVideoComplete() {
                if (adListener != null) {
                    adListener.onVideoComplete(adContentEntity.advertisingId,-1);
                }
            }

            @Override
            public void onADClose() {
                if (adListener != null) {
                    adListener.onVideoComplete(adContentEntity.advertisingId,-1);
                }
            }

            @Override
            public void onError(AdError adError) {
                LogUtils.e("onError addRewardVideo" + ",message=" + adError.getErrorMsg() + ",code=" + adError.getErrorCode());
                if (adListener != null) {
                    adListener.onFail();
                }
            }
        });
        rewardVideoAD.loadAD();
    }


    /**
     * 加载穿山开屏甲短视频广搞
     * setExpressViewAcceptedSize  如果高度设置为0（自适应，无法监听视频完成），建议是屏幕高度
     */
    private void adRewardVideoC() {
        //step3:创建广告请求参数AdSlot,具体参数含义参考文档
        float expressViewWidth = UIUtils.getScreenWidthDp(weakReference.get());
        float expressViewHeight = UIUtils.getHeight(weakReference.get());

        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(adContentEntity.advertisingId) //广告位id 946024371
                .setSupportDeepLink(true)
                .setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(expressViewWidth, expressViewHeight) //期望模板广告view的size,单位dp
                .setUserID(AppConfig.AD_USER_ID)
                .build();

        //在合适的时机申请权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题
        TTAdSdk.getAdManager().requestPermissionIfNecessary(weakReference.get());


        //step4:请求广告,对请求回调的广告作渲染处理
        mTTAdNative.loadExpressDrawFeedAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
                Log.e(TAG, message);
                if (adListener != null) {
                    adListener.onFail();
                }
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.isEmpty()) {
                    Log.e(TAG, "ads == null  || ads is empty");
                    return;
                }
                for (final TTNativeExpressAd ad : ads) {
                    //点击监听器必须在getAdView之前调
                    ad.setVideoAdListener(new TTNativeExpressAd.ExpressVideoAdListener() {
                        @Override
                        public void onVideoLoad() {
                            Log.e(TAG, "onVideoLoad");
                        }

                        @Override
                        public void onVideoError(int errorCode, int extraCode) {
                            Log.e(TAG, "onVideoError");
                        }

                        @Override
                        public void onVideoAdStartPlay() {
                            Log.e(TAG, "onVideoAdStartPlay");
                        }

                        @Override
                        public void onVideoAdPaused() {
                            Log.e(TAG, "onVideoAdPaused");
                        }

                        @Override
                        public void onVideoAdContinuePlay() {
                            Log.e(TAG, "onVideoAdContinuePlay");
                        }

                        @Override
                        public void onProgressUpdate(long current, long duration) {
                        }

                        @Override
                        public void onVideoAdComplete() {
                            if (adListener != null) {
                                adListener.onVideoComplete(adContentEntity.advertisingId,showType);
                            }
                            Log.e(TAG, "onVideoAdComplete");
                        }

                        @Override
                        public void onClickRetry() {
                            Log.e(TAG, "onClickRetry!");
                        }
                    });
                    ad.setCanInterruptVideoPlay(true);

                    ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
                        @Override
                        public void onAdClicked(View view, int type) {
                            Log.e("展示 dianji type = ",""+type);
                        }

                        @Override
                        public void onAdShow(View view, int type) {
                            Log.e("展示 type = ",""+type);
                            showType = type;
                        }

                        @Override
                        public void onRenderFail(View view, String msg, int code) {
                            if (adListener != null) {
                                adListener.onFail();
                            }
                        }

                        @Override
                        public void onRenderSuccess(View view, float width, float height) {
                            if (adListener != null) {
                                adListener.onSuccess(view);
                            }
                            //在渲染成功回调时展示广告，提升体验
                            ad.showInteractionExpressAd(weakReference.get());
                        }
                    });
                    ad.render();
                }
            }
        });
    }

    /**
     * 清空数据
     */
    public void clear() {
        mTTAdNative = null;
        mttRewardVideoAd = null;
    }

    public interface AdListener {
        /**
         * 广告加载成功
         */
         void onSuccess(View view);
        /**
         * 广告加载失败
         */
         void onFail();
        /**
         * 广告播放完成
         */
         void onVideoComplete(String codeId,int type);
    }

}
